package product.service.impl;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import product.domain.*;
import product.domain.SkuInfo;
import product.service.*;
import product.votmp.item.*;
import product.votmp.list.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Service
public class TempServiceImpl implements TempService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private AttrService attrService;

    @Autowired
    private AttrAttrgroupRelationService attrAttrgroupRelationService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private ThreadPoolExecutor executor;

    @Override
    public ListVo getSearchInfo(SearchParamsVo searchParamsVo) {
        ListVo listVo = new ListVo();

        // attrLIst属性信息
        LambdaQueryWrapper<Attr> attrQueryWrapper = getAttrQueryWrapper(searchParamsVo);
        List<Attr> attrList = attrService.list(attrQueryWrapper);
        List<AttrsList> attrsListList = attrList.stream().map(item -> {
            AttrsList attrsList = new AttrsList();
            List<String> attrValueList = Arrays.asList(item.getValueSelect().split(";"));
            attrsList.setAttrValueList(attrValueList);
            attrsList.setAttrId(item.getAttrId());
            attrsList.setAttrName(item.getAttrName());
            return attrsList;
        }).collect(Collectors.toList());
        listVo.setAttrsList(attrsListList);

        // goodsList（skuInfo）商品信息
        LambdaQueryWrapper<SkuInfo> skuInfoWrapper = getSkuInfoWrapper(searchParamsVo);
        Page<SkuInfo> page = new Page<>(searchParamsVo.getPageNo(), searchParamsVo.getPageSize());
        Page<SkuInfo> skuInfoPage = skuInfoService.page(page, skuInfoWrapper);
        //List<SkuInfo> skuInfoList = skuInfoService.list(skuInfoWrapper);
        List<GoodsList> goodsListList = skuInfoPage.getRecords().stream().map(item -> {
            GoodsList goodsList = new GoodsList();
            goodsList.setDefaultImg(item.getSkuDefaultImg());
            goodsList.setId(item.getSkuId());
            goodsList.setPrice(item.getPrice());
            goodsList.setTitle(item.getSkuTitle());
            goodsList.setHotScore(0);
            return goodsList;
        }).collect(Collectors.toList());
        listVo.setGoodsList(goodsListList);

        // trademarkList品牌信息
        LambdaQueryWrapper<CategoryBrandRelation> brandWrapper = getBrandWrapper(searchParamsVo);
        List<Brand> brands = categoryBrandRelationService.getBrandsByWrapper(brandWrapper);
        List<TrademarkList> trademarkListList = brands.stream().map(item -> {
            TrademarkList trademarkList = new TrademarkList();
            trademarkList.setTmId(item.getBrandId());
            trademarkList.setTmName(item.getName());
            return trademarkList;
        }).collect(Collectors.toList());
        listVo.setTrademarkList(trademarkListList);
        // pageNo分页信息
        listVo.setPageNo(skuInfoPage.getCurrent());
        // pageSize
        listVo.setPageSize(skuInfoPage.getPages());
        // total
        listVo.setTotal(skuInfoPage.getTotal());
        // totalPages
        return listVo;
    }

    @Override
    public SkuInfoVo getBySkuId(Long skuId) throws ExecutionException, InterruptedException {
        SkuInfoVo skuInfoVo = new SkuInfoVo();
        // 使用异步编排
        // 第一步，获取skuInfo
        CompletableFuture<SkuInfo> skuInfoFuture = CompletableFuture.supplyAsync(() -> {
            // price
            SkuInfo skuInfo = skuInfoService.getById(skuId);
            skuInfoVo.setPrice(skuInfo.getPrice());
            return skuInfo;
        }, executor);

        // 第二步，设置三级分类的路径信息
        CompletableFuture<Long> category3IdFuture = skuInfoFuture.thenApplyAsync((res) -> {
            // categoryView,三级分类路径信息
            CategoryView categoryView = new CategoryView();
            Long category3Id = res.getCatalogId();
            List<Category> categoryPath = categoryService.findCategoryPath(category3Id);
            categoryView.setCategory3Id(category3Id);
            categoryView.setCategory3Name(categoryPath.get(0).getName());
            categoryView.setCategory2Id(categoryPath.get(1).getCatId());
            categoryView.setCategory2Name(categoryPath.get(1).getName());
            categoryView.setCategory1Id(categoryPath.get(2).getCatId());
            categoryView.setCategory1Name(categoryPath.get(2).getName());
            categoryView.setId(category3Id);
            skuInfoVo.setCategoryView(categoryView);
            return category3Id;
        }, executor);

        CompletableFuture<List<SkuSaleAttrValue>> saleAttrValueListFuture = skuInfoFuture.thenCombineAsync(category3IdFuture, (skuInfo, category3Id) -> {
            // skuInfo-》sku的基本信息
            product.votmp.item.SkuInfo skuInfoTem = new product.votmp.item.SkuInfo();
            skuInfoTem.setCategory3Id(category3Id);
            skuInfoTem.setCreateTime(new Date());
            skuInfoTem.setId(skuId);
            //skuInfoTem.setIsSale(1);
            skuInfoTem.setPrice(skuInfo.getPrice());
            List<SkuAttrValueList> skuAttrValueLists = new ArrayList<>();
            List<SkuSaleAttrValue> skuSaleAttrValueList = skuSaleAttrValueService.list(new LambdaQueryWrapper<SkuSaleAttrValue>().eq(SkuSaleAttrValue::getSkuId, skuId));
            for (SkuSaleAttrValue skuSaleAttrValue : skuSaleAttrValueList) {
                SkuAttrValueList skuAttrValue = new SkuAttrValueList();
                skuAttrValue.setSkuId(skuSaleAttrValue.getSkuId());
                skuAttrValue.setAttrId(skuSaleAttrValue.getAttrId());
                skuAttrValue.setAttrName(skuSaleAttrValue.getAttrName());
                skuAttrValue.setValueName(skuSaleAttrValue.getAttrValue());
                //skuAttrValue.setValueId();
                skuAttrValueLists.add(skuAttrValue);
            }
            skuInfoTem.setSkuAttrValueList(skuAttrValueLists);
            skuInfoTem.setSkuDefaultImg(skuInfo.getSkuDefaultImg());
            skuInfoTem.setSkuDesc(skuInfo.getSkuDesc());

            // SkuImageList商品图片
            List<SkuImageList> skuImageLists = new ArrayList<>();
            List<SkuImages> images = skuImagesService.list(new LambdaQueryWrapper<SkuImages>().eq(SkuImages::getSkuId, skuId));
            for (SkuImages image : images) {
                SkuImageList skuImage = new SkuImageList();
                skuImage.setId(image.getId());
                //skuImage.setImgName(image);
                skuImage.setImgUrl(image.getImgUrl());
                skuImage.setSkuId(skuId);
                //skuImage.setSpuImgId();
                skuImageLists.add(skuImage);
            }
            skuInfoTem.setSkuImageList(skuImageLists);
            skuInfoTem.setSkuName(skuInfo.getSkuName());
            skuInfoTem.setSpuId(skuInfo.getSpuId());
            skuInfoTem.setTmId(skuInfo.getBrandId());
            //skuInfoTem.setWeight(skuInfo.get);
            skuInfoVo.setSkuInfo(skuInfoTem);
            return skuSaleAttrValueList;
        }, executor);

        CompletableFuture<Void> spuSaleAttrFuture = saleAttrValueListFuture.thenAcceptBothAsync(skuInfoFuture, (skuSaleAttrValueList, skuInfo) -> {
            // spuSaleAttrList
            List<SpuSaleAttrList> spuSaleAttrLists = new ArrayList<>();
            // 该商品的销售属性
            for (SkuSaleAttrValue skuSaleAttrValue : skuSaleAttrValueList) {
                SpuSaleAttrList spuSaleAttr = new SpuSaleAttrList();
                spuSaleAttr.setBaseSaleAttrId(skuSaleAttrValue.getAttrId());
                spuSaleAttr.setId(skuSaleAttrValue.getId());
                spuSaleAttr.setSaleAttrName(skuSaleAttrValue.getAttrName());
                spuSaleAttr.setSpuId(skuInfo.getSpuId());
                // 该销售属性所有的值
                Attr attr = attrService.getOne(new LambdaQueryWrapper<Attr>().eq(Attr::getAttrId, skuSaleAttrValue.getAttrId()));
                // 分隔出所有的值
                String[] attrValues = attr.getValueSelect().split(";");
                List<SpuSaleAttrValueList> spuSaleAttrValueList = new ArrayList<>();
                for (String attrValue : attrValues) {
                    SpuSaleAttrValueList spuSaleAttrValue = new SpuSaleAttrValueList();
                    spuSaleAttrValue.setBaseSaleAttrId(skuSaleAttrValue.getAttrId());
                    //spuSaleAttrValueList.setId();
                    //spuSaleAttrValueList.setIsChecked();
                    spuSaleAttrValue.setSaleAttrName(skuSaleAttrValue.getAttrName());
                    spuSaleAttrValue.setSaleAttrValueName(attrValue);
                    spuSaleAttrValue.setSpuId(skuInfo.getSpuId());
                    spuSaleAttrValueList.add(spuSaleAttrValue);
                }
                spuSaleAttr.setSpuSaleAttrValueList(spuSaleAttrValueList);
                spuSaleAttrLists.add(spuSaleAttr);
            }
            skuInfoVo.setSpuSaleAttrList(spuSaleAttrLists);
        }, executor);

        // 等待所有future执行完成，最后返回结果。
        CompletableFuture.allOf(spuSaleAttrFuture).get();

        return skuInfoVo;
    }

    // 封装查询条件
    private LambdaQueryWrapper<Attr> getAttrQueryWrapper(SearchParamsVo searchParamsVo) {
        LambdaQueryWrapper<Attr> wra = new LambdaQueryWrapper<>();
        // 按分类筛选属性
        Long catId;
        if (!ObjUtil.isEmpty(searchParamsVo.getCategory1Id())) {
            catId = searchParamsVo.getCategory1Id();
        } else if (!ObjUtil.isEmpty(searchParamsVo.getCategory2Id())) {
            catId = searchParamsVo.getCategory2Id();
        } else if (!ObjUtil.isEmpty(searchParamsVo.getCategory3Id())) {
            catId = searchParamsVo.getCategory3Id();
        } else {
            // 都为空
            catId = 0L;
        }
        wra.eq(Attr::getCatelogId, catId);
        // 按属性筛选属性
        // 如果props不为空，需要加入筛选条件
        if (!ObjectUtils.isEmpty(searchParamsVo.getProps())) {
            List<String> props = searchParamsVo.getProps();
            // "106:苹果手机:手机系统" 属性id：属性值：属性名称
            for (String prop : props) {
                List<String> list = Arrays.asList(prop.split(":"));
                String attrId = list.get(0);
                String attrValue = list.get(1);
                String attrName = list.get(2);
                wra.eq(Attr::getAttrId, attrId);
                wra.or();
            }
        }
        // todo 按品牌筛选属性

        return wra;
    }

    private LambdaQueryWrapper<CategoryBrandRelation> getBrandWrapper(SearchParamsVo searchParamsVo) {
        LambdaQueryWrapper<CategoryBrandRelation> brandLambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 按分类筛选品牌
        Long catId;
        if (!ObjUtil.isEmpty(searchParamsVo.getCategory1Id())) {
            catId = searchParamsVo.getCategory1Id();
        } else if (!ObjUtil.isEmpty(searchParamsVo.getCategory2Id())) {
            catId = searchParamsVo.getCategory2Id();
        } else if (!ObjUtil.isEmpty(searchParamsVo.getCategory3Id())) {
            catId = searchParamsVo.getCategory3Id();
        } else {
            // 都为空
            catId = 0L;
        }
        if (catId != 0L) {
            brandLambdaQueryWrapper.eq(CategoryBrandRelation::getCatelogId, catId);
        }

        // 按关键词筛选品牌
        if (!ObjectUtils.isEmpty(searchParamsVo.getKeyword())) {
            brandLambdaQueryWrapper.like(CategoryBrandRelation::getBrandName, searchParamsVo.getKeyword());
        }

        // 按品牌筛选品牌
        // 点击了哪个品牌，就排除掉哪个品牌。
        if (!ObjectUtils.isEmpty(searchParamsVo.getTrademark())) {
            String trademark = searchParamsVo.getTrademark();
            List<String> list = Arrays.asList(trademark.split(":"));
            brandLambdaQueryWrapper.ne(CategoryBrandRelation::getBrandId, Long.parseLong(list.get(0)));
        }
        // todo 按属性筛选品牌

        return brandLambdaQueryWrapper;
    }

    private LambdaQueryWrapper<SkuInfo> getSkuInfoWrapper(SearchParamsVo searchParamsVo) {
        LambdaQueryWrapper<SkuInfo> skuInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 按分类筛选商品
        Long catId;
        if (!ObjUtil.isEmpty(searchParamsVo.getCategory1Id())) {
            catId = searchParamsVo.getCategory1Id();
        } else if (!ObjUtil.isEmpty(searchParamsVo.getCategory2Id())) {
            catId = searchParamsVo.getCategory2Id();
        } else if (!ObjUtil.isEmpty(searchParamsVo.getCategory3Id())) {
            catId = searchParamsVo.getCategory3Id();
        } else {
            // 都为空
            catId = 0L;
        }
        if (catId != 0L) {
            skuInfoLambdaQueryWrapper.eq(SkuInfo::getCatalogId, catId);
        }

        // 按关键词筛选商品
        if (!ObjectUtils.isEmpty(searchParamsVo.getKeyword())) {
            skuInfoLambdaQueryWrapper.like(SkuInfo::getSkuName, searchParamsVo.getKeyword())
                    .or()
                    .like(SkuInfo::getSkuDesc, searchParamsVo.getKeyword())
                    .or()
                    .like(SkuInfo::getSkuSubtitle, searchParamsVo.getKeyword());
        }

        // 按属性筛选商品列表
        // 如果props不为空，需要加入筛选条件
        if (!ObjectUtils.isEmpty(searchParamsVo.getProps())) {
            List<String> props = searchParamsVo.getProps();
            // "106:苹果手机:手机系统" 属性id：属性值：属性名称
            for (String prop : props) {
                List<String> list = Arrays.asList(prop.split(":"));
                String attrId = list.get(0);
                String attrValue = list.get(1);
                String attrName = list.get(2);
                LambdaQueryWrapper<SkuSaleAttrValue> skuSaleAttrValueLambdaQueryWrapper = new LambdaQueryWrapper<>();
                skuSaleAttrValueLambdaQueryWrapper.eq(SkuSaleAttrValue::getAttrId, attrId)
                        .eq(SkuSaleAttrValue::getAttrValue, attrValue)
                        .eq(SkuSaleAttrValue::getAttrName, attrName);
                List<SkuSaleAttrValue> skuSaleAttrValueList = skuSaleAttrValueService.list(skuSaleAttrValueLambdaQueryWrapper);
                if (!ObjectUtils.isEmpty(skuSaleAttrValueList)) {
                    for (SkuSaleAttrValue skuSaleAttrValue : skuSaleAttrValueList) {
                        skuInfoLambdaQueryWrapper.eq(SkuInfo::getSkuId, skuSaleAttrValue.getSkuId());
                        skuInfoLambdaQueryWrapper.or();
                    }
                }
            }
        }
        // 按品牌筛选商品列表
        if (!ObjectUtils.isEmpty(searchParamsVo.getTrademark())) {
            String trademark = searchParamsVo.getTrademark();
            List<String> list = Arrays.asList(trademark.split(":"));
            skuInfoLambdaQueryWrapper.eq(SkuInfo::getBrandId, Long.parseLong(list.get(0)));
        }
        // 商品排序
        if (!ObjectUtils.isEmpty(searchParamsVo.getOrder())) {
            // "1:asc" 综合排序按id排序，价格排序按price排序
            String order = searchParamsVo.getOrder();
            List<String> orderList = Arrays.asList(order.split(":"));
            String orderSort = orderList.get(0);
            String orderType = orderList.get(1);
            if (orderSort.equals("1")) {
                if (orderType.equals("asc")) {
                    skuInfoLambdaQueryWrapper.orderByAsc(SkuInfo::getSkuId);
                } else {
                    skuInfoLambdaQueryWrapper.orderByDesc(SkuInfo::getSkuId);
                }
            } else {
                if (orderType.equals("asc")) {
                    skuInfoLambdaQueryWrapper.orderByAsc(SkuInfo::getPrice);
                } else {
                    skuInfoLambdaQueryWrapper.orderByDesc(SkuInfo::getPrice);
                }
            }
        }
        return skuInfoLambdaQueryWrapper;
    }
}
